<?php
	/**
	 * 基础通用接口
	 *
	 */
	class ApiBasic {

		protected $request = null;// request对象
		protected $command = null;// 当前cmd
		private $requestParams = null;// 公共参数
		private $cmdRequestParams = null;// cmd参数
		protected $login = false;// 是否登录态
        protected  $checkAuth = true;//鉴权
        protected $iplimit = 0;
        protected $classname;
        protected $userinfo=null;

        protected $ipLimit = array(
            "appAction"
        );


		public function __construct(Request $request) {
            $this->request = $request;
			$this->requestParams = $request->requestParams();
//			$this->setUserInfo();
            $this->classname = get_class($this);
		}

		public function dispatch($command) {
            
			$this->command = $command;
			if (is_array($this->cmdCollect) && array_key_exists($command, $this->cmdCollect)) {

				$method = isset($this->cmdCollect[$command]['method'])?$this->cmdCollect[$command]['method']:'errorRequest';
				$needLogin = isset($this->cmdCollect[$command]['login'])&&$this->cmdCollect[$command]['login'];
				$needAuth = isset($this->cmdCollect[$command]['auth'])&&$this->cmdCollect[$command]['auth'];
				if ($method != 'errorRequest' && $needLogin && !$this->login) {
					$userid = $this->requestParams['userid'];
					$utoken = $this->requestParams['utoken'];

					$this->login = Validater::checkToken($userid, $utoken);

					if (!$this->login) {
                        $loginStatus = Status::getStatusCode(Status::USER_NOT_LOGIN);
                        $loginStatus['message'] = '请重新登录';
						return $loginStatus;
					}

                    $this->requestParams['channelid'] = 0;
                    $this->requestParams['username'] = '';

				}
				$this->cmdRequestParams = $this->request->cmdRequestParams($command);

                //记录操作日志
//                $this->operationLog();
				return $this->$method();
			}else {
				return Status::getStatusCode(Status::ERROR_INTERFACE_NOT_EXIST);
			}
		}

		/**
		 * [_get 公共参数]
		 * @param  [type] $key [description]
		 * @return [type]      [description]
		 */
		public function _get($key) {
			if (!$this->requestParams) {
				$this->requestParams = $this->request->requestParams();
			}
			if (isset($this->requestParams[$key])) {
				return $this->requestParams[$key];
			}
			return null;
		}

		/**
		 * [_cget 接口参数]
		 * @param  [type] $key [description]
		 * @return [type]      [description]
		 */
		public function _cget($key) {
			if (!$this->cmdRequestParams) {
				$this->cmdRequestParams = $this->request->cmdRequestParams($this->command);
			}
			$data = &$this->cmdRequestParams;

			if (isset($data[$key]) && array_key_exists($key, $this->request->rsaFields) && $this->request->rsaFields[$key] <= 0) {
				return $data[$key] = $this->request->rsaHandle($this->command, $key);
			}elseif (isset($data[$key]) && array_key_exists($key, $this->request->rsaFields) && $this->request->rsaFields[$key] > 0) {
				return $data[$key];
			}elseif (isset($data[$key])) {
				return $data[$key];
			}else {
			    if (isset(Request::$jsonParams[$key])){
                    return Request::$jsonParams[$key][1];
                }else{
                    return isset($_REQUEST[$key]) ? $_REQUEST[$key] : null;
                }
			}
		}

		/**
		 * [show 成功的返回]
		 * @return [type] [description]
		 */
		public function show($data, $msg = null) {
			$status = Status::getStatusCode(Status::SUCCESS);
			$status['data'] = $data;
			$status['message'] = is_null($msg)?$status['message']:$msg;
			return $status;
		}

		/**
		 * [error 失败的返回]
		 * @param  [type] $code [description]
		 * @return [type]       [description]
		 */
		public function error($msg = '', $data = null, $code = Status::FAIL) {
			$status = Status::getStatusCode($code);
			$status['message'] = is_null($msg)?$status['message']:$msg;
			$status['data'] = is_null($data)?$status['data']:$data;
            if (!isset($status["code"])) {
                $status["code"] = $code;
            }
			return $status;
		}

		/**
		 * [errorRequest 不存在的接口]
		 * @return [type] [description]
		 */
		public function errorRequest() {
			return Status::getStatusCode(Status::ERROR_INTERFACE_NOT_EXIST);
		}

		public function setUserInfo(){
            $userid = trim($_REQUEST['userid']);
            if (empty($userid)){
                return true;
            }
            $this->userinfo = UserService::getUserInfoByQudaoUserid($userid);
            $this->userinfo['agents_role'] = $this->userinfo['agents'];

            //部门管理员权限
            $this->userinfo['isadmin_dep'] = 0;
            //部门管理员权限
            $channelModule = new ChannelModule();
            $depAdmin = $channelModule->getQudaoDepByUserid($this->userinfo['btgouserid']);
            if (!empty($depAdmin)) {
                $this->userinfo['isadmin_dep'] = 1;
                $this->userinfo['agents_role'] = 4;
            }

            //管理员权限
            $this->userinfo['isadmin'] = 0;
            if ($this->userinfo['level'] == 1) {
                $this->userinfo['isadmin'] = 1;
                $this->userinfo['agents_role'] = 5;
            }
            //拿到部门id
            $this->userinfo['depid'] = UserService::getUserDepidByUserid($this->userinfo['btgouserid']);
        }

        /**
         * @return void
         */
        private function operationLog()
        {
            //登录操作无需记录
            if (!in_array($this->command, array(10001))) {
                // 获取操作参数列表
                $method = $_SERVER['REQUEST_METHOD'];
                $params = $method == 'GET' ? json_encode($_GET) : json_encode($_POST);
                // 登录ip
                $ip = AppCommon::getUserIP();
                $userid = $this->userinfo['userid'] ?:0;

                // 操作访问路径
                $route = $_SERVER['SCRIPT_NAME'] . $_SERVER['REQUEST_URI'];

                $model = new OperationModule();
                $model->log($this->command, $route, $ip, $userid, $params);
            }
        }
	}